import time

import pkuseg
import requests

from components.config import WFQ_SOURCE_MYSQL_CONFIG
from utils.db.mysqldb import MysqlDB


class NewMall:
    def __init__(self):
        self._to_db = None
        self.session = requests.session()
        self.session.headers = {
            "Accept": "application/json, text/plain, */*",
            "Accept-Language": "zh-CN,zh;q=0.9,zu;q=0.8,be;q=0.7,en;q=0.6",
            "Authorization": "J6LWqX4SHmkZqoWCjLEDLv+Pue3ersJZzIO5njGjL0zvpA91oeqOpwOKVXr82R7c",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Origin": "https://pdd.dianba6.com",
            "Pragma": "no-cache",
            "Referer": "https://pdd.dianba6.com/",
            "Sec-Fetch-Dest": "empty",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Site": "same-site",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36",
            "encryption": "1750750217_fbCA4elD_6bc94bf299ba30bbb5ebaeaba709a487",
            "sec-ch-ua": '"Google Chrome";v="137", "Chromium";v="137", "Not/A)Brand";v="24"',
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": '"Windows"',
        }

    @property
    def to_db(self):
        if self._to_db is None:
            self._to_db = MysqlDB(
                ip=WFQ_SOURCE_MYSQL_CONFIG["MYSQL_IP"],
                port=WFQ_SOURCE_MYSQL_CONFIG["MYSQL_PORT"],
                db=WFQ_SOURCE_MYSQL_CONFIG["MYSQL_DB"],
                user_name=WFQ_SOURCE_MYSQL_CONFIG["MYSQL_USER_NAME"],
                user_pass=WFQ_SOURCE_MYSQL_CONFIG["MYSQL_USER_PASS"],
            )
        return self._to_db

    def search(self, keywords):

        url = f"https://apipdd.dianba6.com/api/rank/keyword/search_v2?goodsName={keywords}&page=1&filter=0"

        response = self.session.get(url)
        print(response.text)
        resp = response.json()
        datas = (resp.get("data") or {}).get("data")
        fields = [
            "mall_name",
            "mall_id",
            "mall_logo",
            "mall_sale",
            "mall_star",
        ]
        results = []
        for i in datas:
            if i.get("mall_id") is None or i.get("mall_id") == "":
                continue
            if i.get("mall_name") is None or i.get("mall_name") == "":
                continue
            item = {
                **{k: v for k, v in i.items() if k in fields},
                **{
                    "extend_info": i,
                    "mall_url": f"https://mobile.yangkeduo.com/mall_page.html?mall_id={i.get('mall_id')}",
                },
            }
            results.append(item)
        self.to_db.add_batch_smart("net_pdd_mall_id", results, update_columns=fields + ["extend_info", "mall_url"])

    def gen_words(self, text):
        seg = pkuseg.pkuseg()  # 默认通用模型
        words = seg.cut(text)
        return words

    def run(self):
        url = "https://apipdd.dianba6.com/api/industry/goods/hotGoods"
        params = {"page": "1", "main_category": "9", "first_category": "8172", "second_category": "8175"}
        response = self.session.get(url, params=params)
        resp = response.json()
        datas = resp.get("data") or []
        for data in datas:
            for word in self.gen_words(data.get("goods_name")):
                print(word)
                time.sleep(5)
                try:
                    self.search(word)
                except Exception as e:
                    print(e)


if __name__ == "__main__":
    test = NewMall()
    test.run()
